const paperService = require('../../../../services/paper');

Page({
  data: {
    activeTab: 'all',
    papers: [],
    loading: false,
    hasMore: true,
    page: 1,
    size: 10,
    selectedSubject: '全部',
    selectedStatus: '全部试卷',
    searchKeyword: '',
    subjects: ['全部', '语文', '数学', '英语', '专业课'],
    statusList: ['全部试卷', '已发布', '未发布', '已归档']
  },

  onLoad() {
    console.log('页面加载');
    this.loadPaperData();
    this.initQuestions();
  },

  onShow() {
    console.log('页面显示');
    // 每次页面显示时刷新数据
    this.setData({
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData();
    });
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.setData({
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData().then(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  onReachBottom() {
    console.log('触底加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadPaperData();
    }
  },

  async loadPaperData() {
    if (this.data.loading) return;
    
    console.log('开始加载数据', {
      subject: this.data.selectedSubject,
      status: this.data.selectedStatus,
      keyword: this.data.searchKeyword,
      page: this.data.page,
      size: this.data.size
    });
    
    this.setData({ loading: true });
    
    try {
      const result = await paperService.getPaperList({
        subject: this.data.selectedSubject === '全部' ? '' : this.data.selectedSubject,
        status: this.data.selectedStatus === '全部试卷' ? '' : this.data.selectedStatus,
        keyword: this.data.searchKeyword,
        page: this.data.page,
        size: this.data.size
      });
      
      console.log('获取数据结果', result);
      
      if (result.success) {
        const { list, total } = result.data;
        const newPapers = [...this.data.papers, ...list];
        
        console.log('更新数据', {
          newPapers,
          total,
          hasMore: newPapers.length < total
        });
        
        this.setData({
          papers: newPapers,
          hasMore: newPapers.length < total,
          page: this.data.page + 1,
          loading: false
        });
      } else {
        console.error('获取数据失败', result.message);
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载试卷列表失败', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  handleTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    console.log('切换标签', tab);
    this.setData({
      activeTab: tab,
      selectedStatus: tab === 'all' ? '全部试卷' : 
                     tab === 'published' ? '已发布' : 
                     tab === 'draft' ? '未发布' : '已归档',
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData();
    });
  },

  handleSubjectChange(e) {
    const subject = e.currentTarget.dataset.subject;
    console.log('切换学科', subject);
    this.setData({
      selectedSubject: subject,
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData();
    });
  },

  handleStatusChange(e) {
    const status = e.currentTarget.dataset.status;
    console.log('切换状态', status);
    this.setData({
      selectedStatus: status,
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData();
    });
  },

  handleSearch(e) {
    const keyword = e.detail.value;
    console.log('搜索关键词', keyword);
    this.setData({
      searchKeyword: keyword,
      page: 1,
      papers: [],
      hasMore: true
    }, () => {
      this.loadPaperData();
    });
  },

  navigateToCreate() {
    console.log('跳转到创建页面');
    wx.navigateTo({
      url: '/pages/teacher/paper/create/create'
    });
  },

  navigateToEdit(e) {
    const paperId = e.currentTarget.dataset.id;
    console.log('跳转到编辑页面', paperId);
    wx.navigateTo({
      url: `/pages/teacher/paper/edit/edit?id=${paperId}`
    });
  },

  async handleDelete(e) {
    const paperId = e.currentTarget.dataset.id;
    console.log('删除试卷', paperId);
    
    try {
      const res = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这份试卷吗？'
      });
      
      if (res.confirm) {
        const result = await paperService.deletePaper(paperId);
        
        if (result.success) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 重新加载数据
          this.setData({
            page: 1,
            papers: [],
            hasMore: true
          }, () => {
            this.loadPaperData();
          });
        } else {
          wx.showToast({
            title: result.message || '删除失败',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('删除试卷失败', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  async handlePublish(e) {
    const paperId = e.currentTarget.dataset.id;
    console.log('发布试卷', paperId);
    
    try {
      const result = await paperService.publishPaper(paperId);
      
      if (result.success) {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        
        // 重新加载数据
        this.setData({
          page: 1,
          papers: [],
          hasMore: true
        }, () => {
          this.loadPaperData();
        });
      } else {
        wx.showToast({
          title: result.message || '发布失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('发布试卷失败', error);
      wx.showToast({
        title: '发布失败',
        icon: 'none'
      });
    }
  },

  onBackClick() {
    wx.navigateBack();
  },

  // 初始化试题数据
  async initQuestions() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'initQuestions'
      });
      
      if (result.result.success) {
        console.log('初始化试题成功', result.result.data);
      } else {
        console.error('初始化试题失败', result.result.message);
      }
    } catch (error) {
      console.error('调用云函数失败', error);
    }
  }
}); 